package com.huaxinkaiye.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class UtilHelper {
	public static Bitmap getBitmapByUrl(String url) {
		Bitmap bitmap = null;
		try {
			URL url2 = new URL(url);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url2.openConnection();
			httpURLConnection.setReadTimeout(3000);
			int code = httpURLConnection.getResponseCode();
			if (code == 200) {
				bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
			}
		} catch (Exception e) {
			return bitmap;
		}
		return bitmap;
	}

	public static boolean IsHaveInternet(final Context context) {
		try {
			ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = manager.getActiveNetworkInfo();
			return (info != null && info.isConnected());
		} catch (Exception e) {
			return false;
		}
	}

	public static Bitmap comp(Bitmap image) {
		float width = image.getWidth();
		float heigth = image.getHeight();

		float ratio1 = (float) 200 / (float) 162;
		float ratio2 = width / heigth;

		double newWidth = 0;
		double newHeight = 0;
		if (ratio1 >= ratio2) {
			newWidth = 200;
			newHeight = heigth * (200 / width);
		} else {
			newHeight = 162;
			newWidth = width * (162 / heigth);
		}

		// 利用Bitmap位图对象生成缩略图
		image = ThumbnailUtils.extractThumbnail(image, (int) newWidth, (int) newHeight);

		Bitmap output = Bitmap.createBitmap(200, 162, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final Rect src = new Rect(0, 0, 200, 162);
		canvas.drawBitmap(image, src, src, null);

		image.recycle();

		return output;
	}

	/**
	 * 判断是否连接wifi
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		if (mWifi.isConnected()) {
			return true;
		}

		return false;
	}

	public static Bitmap getDiskBitmap(String pathString) {
		Bitmap bitmap = null;
		try {
			File file = new File(pathString);
			if (file.exists()) {
				bitmap = BitmapFactory.decodeFile(pathString);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		return bitmap;
	}

	public static Bitmap getBitmapFromFile(String filename, int width, int height) {
		File dst = new File(filename);
		if (null != dst && dst.exists()) {
			try {
				BitmapFactory.Options opts = null;
				if (width > 0 && height > 0) {
					opts = new BitmapFactory.Options();

					// 设置inJustDecodeBounds为true后，decodeFile并不分配空间，此时计算原始图片的长度和宽度
					opts.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(dst.getPath(), opts);
					// 计算图片缩放比例
					final int minSideLength = Math.min(width, height);
					opts.inSampleSize = computeSampleSize(opts, minSideLength, width * height);

					// 这里一定要将其设置回false，因为之前我们将其设置成了true
					opts.inJustDecodeBounds = false;
					opts.inInputShareable = true;
					opts.inPurgeable = true;
				}
				return BitmapFactory.decodeFile(dst.getPath(), opts);
			} catch (Exception e) {
				e.printStackTrace();
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static Bitmap getBitmapFromFile(File dst, int width, int height) {
		if (null != dst && dst.exists()) {
			try {
				BitmapFactory.Options opts = null;
				if (width > 0 && height > 0) {
					opts = new BitmapFactory.Options();

					// 设置inJustDecodeBounds为true后，decodeFile并不分配空间，此时计算原始图片的长度和宽度
					opts.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(dst.getPath(), opts);
					// 计算图片缩放比例
					final int minSideLength = Math.min(width, height);
					opts.inSampleSize = computeSampleSize(opts, minSideLength, width * height);

					// 这里一定要将其设置回false，因为之前我们将其设置成了true
					opts.inJustDecodeBounds = false;
					opts.inInputShareable = true;
					opts.inPurgeable = true;
				}
				return BitmapFactory.decodeFile(dst.getPath(), opts);
			} catch (Exception e) {
				e.printStackTrace();
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
		return null;
	}


	public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	public static float getRating(String score) {
		float value = Float.parseFloat(score);
		if (value <= 0.9 && value >= 0.1) {
			return 0.5f;
		} else if (value <= 0.9 && value >= 0.1) {
			return 0.5f;
		} else if (value <= 1.9 && value >= 1.1) {
			return 1.5f;
		} else if (value <= 2.9 && value >= 2.1) {
			return 2.5f;
		} else if (value <= 3.9 && value >= 3.1) {
			return 3.5f;
		} else if (value <= 4.9 && value >= 4.1) {
			return 4.5f;
		}

		return value;
	}

	// 获取图片所在文件夹名称
	public static String getDir(String path) {
		String subString = path.substring(0, path.lastIndexOf('/'));
		return subString.substring(subString.lastIndexOf('/') + 1, subString.length());
	}

	public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 生成拍照缓存文件
	 */
	public static Uri generateImageUri() {
		File dir = new File("/sdcard/lijun/");
		if (!dir.exists()) {
			dir.mkdirs();
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");

		File file = new File(dir.getAbsolutePath() + "/" + format.format(Calendar.getInstance().getTime()) + ".jpg");
		return Uri.fromFile(file);
	}

	/**
	 * 从用户相册中选择照片
	 */
	public static void doChoicePhoto(Activity activty, int outputSize, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("return-data", true);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputSize);
		intent.putExtra("outputY", outputSize);
		intent.putExtra("scale", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true);
		activty.startActivityForResult(intent, requestCode);
	}

	/**
	 * 从用户相册中选择照片
	 */
	public static void doChoicePhoto(Activity activty, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("return-data", true);
		activty.startActivityForResult(intent, requestCode);
	}

	/**
	 * 拍照
	 */
	public static void doTakePhoto(Activity activity, int requestCode) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// action is
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 拍照
	 */
	public static void doTakePhoto(Activity activity, Uri imageUri, int requestCode) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// action is
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		activity.startActivityForResult(intent, requestCode);
	}
//
//	/**
//	 * 剪裁照片
//	 */
//	public static void cropImageUri(Activity activity, Bitmap data, int outputSize, int requestCode) {
//		Intent intent = new Intent(activity, CropImage.class);
//		intent.setType("image/*");
//		intent.putExtra("data", data);
//		intent.putExtra("crop", "true");
//		intent.putExtra("aspectX", 1);
//		intent.putExtra("aspectY", 1);
//		intent.putExtra("outputX", outputSize);
//		intent.putExtra("outputY", outputSize);
//		intent.putExtra("scale", true);
//		intent.putExtra("return-data", true);
//		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//		intent.putExtra("noFaceDetection", true); // no face detection
//		activity.startActivityForResult(intent, requestCode);
//	}

	/**
	 * 剪裁照片
	 */
	public static void cropImageUri(Activity activity, Uri uri, int outputSize, int requestCode) {
		// Intent intent = new Intent(activity, CropImage.class);
		// Uri uri = Uri.fromFile(new File(path));
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// intent.putExtra(CropImage.IMAGE_PATH, path);
		/*
		 * try { intent.putExtra("data", Bimp.revitionImageSize(path)); } catch
		 * (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputSize);
		intent.putExtra("outputY", outputSize);
		// intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		// intent.putExtra("return-data", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		activity.startActivityForResult(intent, requestCode);
	}

//	/**
//	 * 剪裁照片
//	 */
//	public static void cropImageUri(Activity activity, String path, int outputSize, int requestCode) {
//		Intent intent = new Intent(activity, CropImage.class);
//		intent.setType("image/*");
//		intent.putExtra(CropImage.IMAGE_PATH, path);
//		intent.putExtra("crop", "true");
//		intent.putExtra("aspectX", 1);
//		intent.putExtra("aspectY", 1);
//		intent.putExtra("outputX", outputSize);
//		intent.putExtra("outputY", outputSize);
//		intent.putExtra("scale", true);
//		intent.putExtra("return-data", true);
//		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//		intent.putExtra("noFaceDetection", true); // no face detection
//		activity.startActivityForResult(intent, requestCode);
//	}

	/**
	 * 从用户相册中选择照片
	 */
	public static void doChoicePhoto(Activity activty, int outputSize, Uri imageUri, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("return-data", true);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputSize);
		intent.putExtra("outputY", outputSize);
		// intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true);
		activty.startActivityForResult(intent, requestCode);
	}

	/**
	 * 获取照片路径
	 */
	public static String getPath(Context context, Uri uri) {
		ContentResolver cr = context.getContentResolver();
		String strPath = "";
		Cursor c = null;
		try {
			if ("content".equalsIgnoreCase(uri.getScheme())) {
				c = cr.query(uri, new String[] { MediaStore.Images.Media.DATA }, null, null, null);
				if (c != null && c.getCount() > 0) {
					if (c.moveToFirst()) {
						strPath = c.getString((c.getColumnIndex(MediaStore.Images.Media.DATA)));
					}
				}
			} else {
				strPath = uri.toString();
			}

			if (strPath.length() != 0) {
				if (strPath.startsWith("file:")) {
					strPath = strPath.replaceFirst("file:", "");
				}
			}
		} catch (Exception ex) {

		} finally {
			if (c != null) {
				c.close();
				c = null;
			}
		}
		return strPath;
	}

	/**
	 * 将图片流转换成Base64字符串
	 * 
	 * @param img
	 * @return
	 */
	public static String getImageBase64(ImageView img) {
		if (img.getTag() == null) {
			return "";
		}

		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);

			return Base64.encodeToString(out.toByteArray(), Base64.DEFAULT);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "";
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static String getImageBase64(Bitmap bitmap) {

		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);

			return Base64.encodeToString(out.toByteArray(), Base64.DEFAULT);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "";
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * MD5 加密
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}

	/**
	 * 获取当前日期是星期几<br>
	 * 
	 * @param dt
	 * @return 当前日期是星期几
	 */
	public static String getWeekOfDate(Date dt) {
		String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return weekDays[w];
	}

	public static boolean isSameDay(Date day1, Date day2) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String ds1 = sdf.format(day1);
		String ds2 = sdf.format(day2);
		if (ds1.equals(ds2)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * cuid（设备唯一标识）生成规则
	 * @param context
	 * @return
	 */
	public static String getDeviceId(Context context) {

		StringBuilder deviceId = new StringBuilder();
		// 渠道标志
		deviceId.append("m");

		try {
			// wifi mac地址
			WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			String wifiMac = info.getMacAddress();
			if (wifiMac != null || !"".equals(wifiMac)) {
				deviceId.append("wifi");
				deviceId.append(wifiMac);
			}

			// IMEI（imei）
			TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			String imei = tm.getDeviceId();
			if (imei != null || !"".equals(imei)) {
				deviceId.append("imei");
				deviceId.append(imei);
			}

			// 序列号（sn）
			String sn = tm.getSimSerialNumber();
			if (sn != null && !"".equals(sn)) {
				deviceId.append("sn");
				deviceId.append(sn);
			}

			// 如果上面都没有， 则生成一个id：随机码
			if (deviceId.toString().length() == 1) {
				String uuid = UUID.randomUUID().toString();
				;
				deviceId.append("id");
				deviceId.append(uuid);
			}

		} catch (Exception e) {
			e.printStackTrace();
			deviceId.append("id").append(UUID.randomUUID().toString());
		}

		String cuid = MD5(deviceId.toString());

		return cuid;

	}

	/**
	 * MD5加密
	 * @param s
	 * @return
	 */
	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取系统语言
	 * @param context
	 * @return
	 */
	public static String getLanguage(Context context){
		Locale locale = context.getResources().getConfiguration().locale;
		return locale.getLanguage();
	}
	
	/**
	 * 当前系统时间，unix时间戳
	 * @return
	 */
	public static String getUnix(){
		try {
			Date date =new Date();

			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return Long.toString((simpleDateFormat.parse(simpleDateFormat.format(date))).getTime()/1000);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";


	}
	
	public static String toURLDecoded(String paramString) {
		if (paramString == null || paramString.equals("")) {
			return "";
		}
		
		try
		{
			String str = new String(paramString.getBytes(), "UTF-8");
			str = URLDecoder.decode(str, "UTF-8");
			return str;
		}
		catch (Exception localException)
		{
			localException.printStackTrace();
		}
		
		return "";
	}
	
	public static String toURLEncoded(String paramString) {  
        if (paramString == null || paramString.equals("")) {  
            return "";  
        }  
          
        try  
        {  
            String str = new String(paramString.getBytes(), "UTF-8");  
            str = URLEncoder.encode(str, "UTF-8");  
            return str;  
        }  
        catch (Exception localException)  
        {  
        	localException.printStackTrace();
        }  
          
        return "";  
    } 
	
	public static String getLanguageText(Context context, String chsText,String enText,String mmText){
		String lang = UtilHelper.getLanguage(context);
		if (lang.equals("zh")){
			return chsText;
		}
		else if (lang.equals("ch")){
			return enText;
		}
		else{
			return mmText;
		}
	}
	
	public static String formatUrl(Context context, String url){
		url += "&cuid="+UtilHelper.getDeviceId(context);
		url += "&os=android";
		url += "&sv="+android.os.Build.VERSION.RELEASE;
		url += "&ossv="+"Android"+Integer.toString(android.os.Build.VERSION.SDK_INT);

		return url;
	}
}